//
//  SJSetNameViewController.m
//  WSL
//
//  Created by CJ on 2018/2/1.
//  Copyright © 2018年 sanjuetech. All rights reserved.
//

#import "SJSetNameViewController.h"
#import "SJUserInfoItem.h"
#import "SJSetUserInfoApi.h"

@interface SJSetNameViewController ()

@property (nonatomic, strong) UIView *navigationBarView;
@property (strong, nonatomic) UIView *bgView;
@property (nonatomic, strong) UITextField *nameField;

@end

@implementation SJSetNameViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [SJStatisticTool beginLogPageView:NSStringFromClass([self class])];
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    
    [SJStatisticTool endLogPageView:NSStringFromClass([self class])];
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self setupUI];
    self.nameField.text = self.myInfo.name;
    [self.nameField becomeFirstResponder];
    
    UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(singleTapAction)];
    singleTap.cancelsTouchesInView = NO;
    [self.view addGestureRecognizer:singleTap];
}

- (void)singleTapAction {
    
    [self.view endEditing:YES];
}


- (void)setupUI {
    
    [self.view addSubview:self.navigationBarView];
    
    if (812 == SJScreenH) {
        self.navigationBarView.sd_layout
        .leftSpaceToView(self.view, SJLayoutFrame(0))
        .topSpaceToView(self.view, SJLayoutFrame(40))
        .heightIs(SJLayoutFrame(50))
        .widthIs(SJScreenW);
    } else {
        self.navigationBarView.sd_layout
        .leftSpaceToView(self.view, SJLayoutFrame(0))
        .topSpaceToView(self.view, SJLayoutFrame(0))
        .heightIs(SJLayoutFrame(50))
        .widthIs(SJScreenW);
    }
    
    [self.view addSubview:self.bgView];
    self.bgView.sd_layout
    .topSpaceToView(self.navigationBarView, SJMargin)
    .leftSpaceToView(self.view, SJMargin)
    .rightSpaceToView(self.view, SJMargin)
    .heightIs(SJItemWH);
    
    [self.bgView addSubview:self.nameField];
    self.nameField.sd_layout.spaceToSuperView(UIEdgeInsetsMake(0, SJMargin, 0, 0));
    
}

#pragma mark - getter

- (UIView *)bgView {
    
    if (!_bgView) {
        
        _bgView = [UIView new];
        _bgView.sd_cornerRadius = @(SJCornerRadius);
        _bgView.backgroundColor = SJColorHexString(@"#ffffff25");        
    }
    return _bgView;
}


- (UIView *)navigationBarView{
    
    if (!_navigationBarView) {
        
        _navigationBarView = [UIView new];
        _navigationBarView.backgroundColor = [UIColor clearColor];
        
        // 返回
        UIButton *backButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [backButton setImage:[UIImage imageNamed:@"addtext-icon-return"] forState:UIControlStateNormal];
        [backButton addTarget:self action:@selector(backAction) forControlEvents:UIControlEventTouchUpInside];
        
        [_navigationBarView addSubview:backButton];
        backButton.sd_layout
        .centerYEqualToView(_navigationBarView)
        .leftSpaceToView(_navigationBarView, SJLayoutFrame(10))
        .heightIs(SJLayoutFrame(30))
        .widthIs(SJLayoutFrame(30));
        
        // 词条输入
        UILabel *wordLabel = [UILabel new];
        wordLabel.textColor = SJColorHexString(@"#ffffff");
        wordLabel.font = [UIFont fontWithName:@"Helvetica" size:SJLayoutFrame(17)];
        wordLabel.textAlignment = NSTextAlignmentCenter;
        wordLabel.text = @"设置昵称";
        
        [_navigationBarView addSubview:wordLabel];
        wordLabel.sd_layout
        .centerYEqualToView(_navigationBarView)
        .centerXEqualToView(_navigationBarView)
        .heightIs(SJLayoutFrame(27));
        [wordLabel setSingleLineAutoResizeWithMaxWidth:SJScreenW * .5];
        
        // 确定
        UIButton *affirmButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [affirmButton setImage:[UIImage imageNamed:@"personal_icon_completed"] forState:UIControlStateNormal];
        [affirmButton addTarget:self action:@selector(affirmAction) forControlEvents:UIControlEventTouchUpInside];
        
        [_navigationBarView addSubview:affirmButton];
        affirmButton.sd_layout
        .centerYEqualToView(_navigationBarView)
        .rightSpaceToView(_navigationBarView, SJLayoutFrame(20))
        .heightIs(SJLayoutFrame(30))
        .widthIs(SJLayoutFrame(60));
        
    }
    return _navigationBarView;
}

- (void)backAction {
    
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)affirmAction {
    
    if (![self.nameField.text isNotBlank]) {
        
        NSString *msg = @"请输入昵称";
        [SVProgressHUD showErrorWithStatus:msg];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [SVProgressHUD dismiss];
        });
        return;
    }
    
    // 1.拼接参数
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"token"] = [SJUserDefaults objectForKey:SJToken];
    parameters[@"name"] = self.nameField.text;
    
    SJSetUserInfoApi *api = [[SJSetUserInfoApi alloc] initWithParameters:parameters];
    [api startWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        
        if ([api.responseObject[@"result"][@"err"] intValue] == 0) {
            
            [SJUserDefaults setObject:api.responseObject[@"content"] forKey:SJUserInfo];
            [SJUserDefaults synchronize];
            
            [SVProgressHUD showSuccessWithStatus:@"修改成功"];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [SVProgressHUD dismiss];
                [self backAction];
            });
        
        } else {
            
            NSString *msg = api.responseObject[@"result"][@"msg"];
            [SVProgressHUD showErrorWithStatus:msg];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [SVProgressHUD dismiss];
            });
            
        }
        
        
        NSMutableDictionary *attributes = [NSMutableDictionary dictionary];
        attributes[@"name"] = @"设置昵称";
        [SJStatisticTool event:@"setname" attributes:attributes];
        
    } failure:^(YTKBaseRequest *request) {
        
    }];
}


- (UITextField *)nameField{
    
    if (!_nameField) {
        
        _nameField = [UITextField new];
        _nameField.returnKeyType = UIReturnKeyDone;
        _nameField.keyboardType = UIKeyboardTypeDefault;
        _nameField.clearButtonMode = UITextFieldViewModeWhileEditing;
        _nameField.textColor = SJColorHexString(@"#ffffff");
        _nameField.font = [UIFont systemFontOfSize:SJLayoutFrame(15)];
        
        // 编辑
//        [_nameField addTarget:self action:@selector(editingDidBegin:) forControlEvents:UIControlEventEditingDidBegin];
//        [_nameField addTarget:self action:@selector(editingDidEnd:) forControlEvents:UIControlEventEditingDidEnd];
        
        NSString *holderText = @"请输入昵称";
        NSMutableAttributedString *placeholder = [[NSMutableAttributedString alloc]initWithString:holderText];
        [placeholder addAttribute:NSForegroundColorAttributeName
                            value:SJColorHexString(@"#ffffff90")
                            range:NSMakeRange(0, holderText.length)];
        [placeholder addAttribute:NSFontAttributeName
                            value:[UIFont systemFontOfSize:SJLayoutFrame(15)]
                            range:NSMakeRange(0, holderText.length)];
        _nameField.attributedPlaceholder = placeholder;
        
    }
    return _nameField;
}

@end
